package com.ypj.rpc.registry;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.ypj.rpc.enumeration.RpcError;
import com.ypj.rpc.exception.RpcException;
import com.ypj.rpc.loaderbalancer.LoaderBalancer;
import com.ypj.rpc.loaderbalancer.RandomLoadBalancer;
import com.ypj.rpc.utils.NacosUtils;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.List;

@Slf4j
public class NacosServiceDiscovery implements ServiceDiscovery {

    //实现负载均衡的算法实现类
    private final LoaderBalancer balancer;

    public NacosServiceDiscovery(LoaderBalancer balancer) {
        if (balancer==null){
            this.balancer=new RandomLoadBalancer();
        }else{
            this.balancer = balancer;
        }
    }


    @Override
    public InetSocketAddress lookup(String serviceName) {
        try {
            List<Instance> instances = NacosUtils.getAllInstance(serviceName);
            if (instances.isEmpty()){
                log.error("找不到对应的服务："+serviceName);
                throw new RpcException(RpcError.SERVICE_NOT_FOUND.getMessage());
            }
            Instance instance= balancer.select(instances);
            return new InetSocketAddress(instance.getIp(),instance.getPort());
        } catch (NacosException e) {
            log.error("获取服务时发生错误：",e);
        }
        return null;
    }
}
